package com.irdstudio.efp.esb.api.rest.sed.credit;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.irdstudio.basic.framework.core.base.FrameworkService;
import com.irdstudio.basic.framework.core.constant.ESBConstant;
import com.irdstudio.basic.framework.core.constant.EsbRetCodeStandard;
import com.irdstudio.basic.framework.core.constant.SDicToExternalConstant;
import com.irdstudio.basic.framework.core.exception.BizException;
import com.irdstudio.basic.framework.core.util.sdic.SDicToExternal;
import com.irdstudio.basic.sequence.service.DefaultPatternDescriptor;
import com.irdstudio.basic.sequence.service.PatternDescriptor;
import com.irdstudio.efp.esb.api.bean.sed.credit.req.ReqSedCreditQueryBean;
import com.irdstudio.efp.esb.api.bean.sed.credit.resp.RespSedCreditQueryBean;
import com.irdstudio.efp.esb.api.bean.sed.other.RespSedNlsCreditInfoBean;
import com.irdstudio.efp.esb.api.common.EsbRespServiceBeanCreator;
import com.irdstudio.efp.esb.api.common.sed.SedCreditQueryTypeEnum;
import com.irdstudio.efp.esb.api.service.sed.credit.NlsSedCreditQueryService;
import com.irdstudio.efp.esb.common.constant.EsbBizEnums;
import com.irdstudio.efp.esb.common.constant.EsbSysHeadEnums;
import com.irdstudio.efp.esb.common.server.req.EsbReqServiceBean;
import com.irdstudio.efp.esb.common.server.resp.EsbRespServiceBean;
import com.irdstudio.efp.nls.service.facade.sx.NlsCreditInfoService;
import com.irdstudio.efp.nls.service.vo.sx.NlsCreditInfoVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static com.irdstudio.basic.sequence.service.DefaultPatternDescriptor.SEQ;

/**
* 普税贷产品对税e贷产品的此部分代码做了复用
* 说明：为了保证功能的复用性、提升开发的工作效率，对该代码进行了复用
* 评估是否会影响线上功能：否
* 评估时间：2020/5/25
* 处理方案：保留复用
*/
/**
 * 服务名称 ：30230003(贷款基本信息查询)<br>
 * 服务场景名称：03（个人授信申请查询） <br>
 * 服务描述： 查询贷款的基本信息<br>
 * 服务场景描述：渠道接收授信申请后，查询该客户的授信申请信息，判断该客户已做过授信：如果授信信息为空则进入授信申请界面；
 * 	     如果有授信信息则根据授信审批状态（如果为通过则调用额度信息查询进入下一步骤；如果为其他状态则返回处理结果。） <br>
 * @author zhoucs1
 * @version 1.0
 * @since 2019年4月17日 上午09:19:00
 * 
 */
@RestController
@RequestMapping("/esb")
public class NlsSedCreditQueryController implements FrameworkService {
	private static Logger logger = LoggerFactory.getLogger(NlsSedCreditQueryController.class);
	public static final PatternDescriptor PATTERN = DefaultPatternDescriptor.of("S" + SEQ, 9);
	
	//默认第一页
	private final String DEFAULT_PAGE_NO = "1";
	//默认每页显示10条记录
	private final String DEFAULT_PAGE_SIZE = "10";
	// 数字正则表达式
	private final String NUM_RGX = "^[1-9]{1}[0-9]*$";

	/**
	 * 获取ESB请求对象，校验 ESB请求系统头和请求应用头对象
	 * 
	 * @param request
	 *            请求对象集合
	 * @return
	 * @author huangwb
	 * @since 2019年1月20日 下午1:28:08
	 * @version 1.0
	 */
	@ModelAttribute("esbReqServiceBean")
	public EsbReqServiceBean getReqEsbHeadBean(HttpServletRequest request) {
		logger.info("校验 ESB请求系统头和请求应用头对象!");
		EsbReqServiceBean esbReqServiceBean = (EsbReqServiceBean) request.getAttribute("esbReqServiceBean");
		return esbReqServiceBean;
	}

	/**
	 * 获取ESB请求对象，校验 ESB请求体对象
	 * 
	 * @param request
	 *            请求对象集合
	 * @return
	 * @author huangwb
	 * @since 2019年1月20日 下午1:31:14
	 * @version 1.0
	 */
	@ModelAttribute("reqSedCreditQueryBean")
	public ReqSedCreditQueryBean getReqEsbBodyBean(HttpServletRequest request) {
		logger.info("校验 ESB请求体对象！");
		String esbReqBody = (String) request.getAttribute("esbReqBody");
		return JSONObject.parseObject(esbReqBody, ReqSedCreditQueryBean.class,Feature.InternFieldNames);
	}
	
	/**
	 * 
	 * @param esbReqServiceBean
	 *            ESB请求对象
	 * @param br1
	 * @param reqSedCreditQueryBean
	 *            ESB请求体的对象
	 * @param br2
	 * @param exception
	 *            切面的异常信息
	 * @return
	 * @throws Exception
	 * @author zhoucs1
	 * @since 2019年4月17日 上午09:34:00
	 * @version 1.0
	 */
	@PostMapping("/SERVICE_30230003_03")
	public EsbRespServiceBean doRecv(@Validated @ModelAttribute("esbReqServiceBean") EsbReqServiceBean esbReqServiceBean, BindingResult br1,
                                     @Validated @ModelAttribute("reqSedCreditQueryBean") ReqSedCreditQueryBean reqSedCreditQueryBean, BindingResult br2, Exception exception) throws Exception {
		logger.info("授信查询开始");
		String qryType = reqSedCreditQueryBean.getQryType(); /*查询类型*/
		String pageNo = reqSedCreditQueryBean.getPageNo(); /*页码*/
		String pageSize = reqSedCreditQueryBean.getPageSize(); /*每页显示条数*/
		
		//响应体
		RespSedCreditQueryBean respSedCreditQueryBean = new RespSedCreditQueryBean();
		logger.info("开始校验请求参数");
		try {
			if(Objects.nonNull(exception)) {
				throw new BizException(exception.getMessage());
			}

			if ("1".equals(reqSedCreditQueryBean.getIsCheckMobile())) {
				//如果校验手机号的话
				if (StringUtils.isBlank(reqSedCreditQueryBean.getMobile())) {
					throw new BizException("手机号不能为空");
				}
			}

            //给授信查询设置不同的查询参数
			NlsCreditInfoVO nlsCreditInfoVO = new NlsCreditInfoVO();
			
			//处理请求参数获取查询结果
			logger.info("校验请求参数完毕，开始查询数据");
			List<NlsCreditInfoVO> nlsCreditInfoVOList = nlsSedCreditQueryService.transferQueryParams(nlsCreditInfoVO,qryType,reqSedCreditQueryBean);

			//校验手机号
			if ("1".equals(reqSedCreditQueryBean.getIsCheckMobile())) {
				if (nlsCreditInfoVOList != null) {
					for (NlsCreditInfoVO creditInfoVO : nlsCreditInfoVOList) {
						if (!reqSedCreditQueryBean.getMobile().equals(creditInfoVO.getIndivMobile())) {
							throw new BizException("录入手机号跟预留手机号不一致");
						}
					}
				}
			}

			Integer totalSize = nlsCreditInfoVOList.size();
			
			//获取zx30Days的数据，30天内：1、跑过征信查询的插槽；2、30内授信有被拒绝过
			String zx30Days = "N";
			if(!SedCreditQueryTypeEnum.QUERY_TYPE_01.getValue().equals(qryType)) {
				zx30Days = nlsSedCreditQueryService.queryZx30DaysStatus(reqSedCreditQueryBean);
				//zx30Days = nlsSedCreditQueryService.queryZx30DaysStatus(reqSedCreditQueryBean);
				zx30Days = nlsSedCreditQueryService.approve30Query(reqSedCreditQueryBean);
			}
			
			//处理授信查询结果
			nlsCreditInfoVOList = nlsSedCreditQueryService.handleResultList(nlsCreditInfoVOList,qryType,pageNo,pageSize);
			List<RespSedNlsCreditInfoBean> respSedNlsCreditInfoList = (List<RespSedNlsCreditInfoBean>) beansCopy(nlsCreditInfoVOList,RespSedNlsCreditInfoBean.class);
			logger.info("授信查询到的记录条数为" + nlsCreditInfoVOList.size());
			
			
			logger.info("开始处理要返回的数据");
			respSedCreditQueryBean.setPageNo((pageNo == null || "".equals(pageNo) || !pageNo.matches(NUM_RGX)) ? DEFAULT_PAGE_NO : pageNo);
			respSedCreditQueryBean.setTotalSize(totalSize.toString());
			respSedCreditQueryBean.setPageSize((pageSize == null || "".equals(pageSize) || !pageSize.matches(NUM_RGX)) ? DEFAULT_PAGE_SIZE : pageSize);
			if(!SedCreditQueryTypeEnum.QUERY_TYPE_01.getValue().equals(qryType)) {
				respSedCreditQueryBean.setZx30days(zx30Days);
			}
			respSedCreditQueryBean.setNlsCrediApplArr(respSedNlsCreditInfoList);
			//如果查询到的记录不为空，则设置查询到的客户信息，否则返回上送的客户信息
			if(!nlsCreditInfoVOList.isEmpty()) {
				NlsCreditInfoVO innerNlsCreditInfoVO = nlsCreditInfoVOList.get(0);
				respSedCreditQueryBean.setCertType(innerNlsCreditInfoVO.getCertType());
				respSedCreditQueryBean.setCertCode(innerNlsCreditInfoVO.getCertCode());
				respSedCreditQueryBean.setCusId(innerNlsCreditInfoVO.getCusId());
				respSedCreditQueryBean.setCusName(innerNlsCreditInfoVO.getCusName());
			} else {
				respSedCreditQueryBean.setCertType(reqSedCreditQueryBean.getCertType());
				respSedCreditQueryBean.setCertCode(reqSedCreditQueryBean.getCertCode());
				respSedCreditQueryBean.setCusId(reqSedCreditQueryBean.getCusId());
				respSedCreditQueryBean.setCusName("");
				
			}
			respSedCreditQueryBean.setRetCode(ESBConstant.SUCCESS);
			respSedCreditQueryBean.setRetMsg("查询成功");
			logger.info("要返回的数据处理结束");
			
		 }  catch (Exception ex) {
			logger.error("授信查询接口出现异常，异常信息为：",ex.getMessage());
			logger.info("异常返回信息处理开始");
			respSedCreditQueryBean.setPageNo(pageNo);
			//当返回异常时，设置查询到的记录数为0
			respSedCreditQueryBean.setTotalSize("0");
			respSedCreditQueryBean.setPageSize(pageSize);
			//发生异常时，按照上送的消息返回
			respSedCreditQueryBean.setCertType(reqSedCreditQueryBean.getCertType());
			respSedCreditQueryBean.setCertCode(reqSedCreditQueryBean.getCertCode());
			respSedCreditQueryBean.setCusId(reqSedCreditQueryBean.getCusId());
			respSedCreditQueryBean.setCusName("");
			if(!SedCreditQueryTypeEnum.QUERY_TYPE_01.getValue().equals(qryType)) {
				respSedCreditQueryBean.setZx30days("N");
			}
			
			respSedCreditQueryBean.setNlsCrediApplArr(new ArrayList<RespSedNlsCreditInfoBean>());
			logger.info("异常返回信息处理结束");
			respSedCreditQueryBean.setRetMsg(ex.getMessage());
			ex.printStackTrace();
			if(ex instanceof BizException) {  //参数校验错误的异常
				respSedCreditQueryBean.setRetCode(EsbRetCodeStandard.JKYDCSJYBTG.getValue());
				return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
						JSONObject.toJSONString(respSedCreditQueryBean,true), 
						EsbSysHeadEnums.RetStEnum.FAILURE.getCode(), //
						EsbRetCodeStandard.JKYDCSJYBTG.getValue(), // 参数校验不通过
						ex.getMessage());
			} else {
				respSedCreditQueryBean.setRetCode(EsbRetCodeStandard.SJCLYC.getValue());
				return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
						JSONObject.toJSONString(respSedCreditQueryBean,true), 
						EsbSysHeadEnums.RetStEnum.FAILURE.getCode(), //
						EsbRetCodeStandard.SJCLYC.getValue(), // 数据处理异常
						ex.getMessage());
			}
		}
		//转换币种
		logger.info("授信查询处理成功");
		List<RespSedNlsCreditInfoBean> nlsCrediApplArr = respSedCreditQueryBean.getNlsCrediApplArr();
		if (nlsCrediApplArr != null) {
			for (RespSedNlsCreditInfoBean respSedNlsCreditInfoBean : nlsCrediApplArr) {
				respSedNlsCreditInfoBean.setCurrencyType(SDicToExternal.getExternalSysDicVal(SDicToExternalConstant.SYSID_IFP, SDicToExternalConstant.CUR_TYPE, respSedNlsCreditInfoBean.getCurrencyType()));
			}
		}
		return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
				JSONObject.toJSONString(respSedCreditQueryBean,true), 
				EsbSysHeadEnums.RetStEnum.SUCCESS.getCode(), //
				EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(), //
				"查询成功");

	}
	@Autowired
	@Qualifier("nlsCreditInfoService")
	private NlsCreditInfoService nlsCreditInfoService;
	@Autowired
	@Qualifier("nlsSedCreditQueryService")
	private NlsSedCreditQueryService nlsSedCreditQueryService;
}
